﻿var flag_insert = 0;
$(function () {
    var uploaderImg = createUploader(
            document.getElementById('upload_img'),
            '../DataService.asmx/InsertUpdateSponsor',
            { SponsorName: "", LinkToSite: "", SponsorType: "", ID: "" },
            ['jpg', 'png'],
            "Upload image",
            function () {
                $('#upload_img_error').css('display', 'none');
            }
        );


    $('#ddlTypes').empty();
    ajaxCall('../DataService.asmx/GetAllSponsorTypes', false, "",
            function (msg) {
                for (var i = 0; i < msg.d.length; i++) {
                    $('#ddlTypes').append(new Option(msg.d[i].Name, msg.d[i].ID));

                }
            },
            function () {
                alert("Error happend while reading from database");
            }
        );

    getAllSponsors();



    $('#btnCancel').click(function (e) {
        $('#insertSponsor').dialog("close");
    });

    $('#btnInsert').click(function (e) {
        $('#validateSponsor').validate({
            rules: {
                sponsorname: "required",
                sponsorlink: {
                    required:true,
                    url:true
                }
            },

            messages: {
                sponsorname: "Sponsor name is required",
                sponsorlink: {
                    required: "Link to web site is required",
                    url: "Wrong url parametar"
                }
            },

            errorPlacement: function (error, element) {
                error.insertAfter(element);
            }

        });


        if ($('#txtName').valid() && $('#txtLink').valid()) {
            uploaderImg._options.params.SponsorName = $('#txtName').val();
            uploaderImg._options.params.LinkToSite = $('#txtLink').val();
            uploaderImg._options.params.SponsorType = $('#ddlTypes').val();
            uploaderImg._options.params.ID = flag_insert;
            if (flag_insert != 0) {
                if (uploaderImg.uploadStoredFiles()) {
                    $('#insertSponsor').dialog("close");
                    $('#txtName').val("");
                    $('#txtLink').val("");
                    getAllSponsors();
                }
                else {
                    var data = '{"ID":"' + flag_insert + '", "SponsorName":"' + $('#txtName').val() + '", "LinkToSite":"' + $('#txtLink').val() + '", "SponsorType":"' + $('#ddlTypes').val() + '"}';
                    ajaxCall('../DataService.asmx/UpdateSponsorNoImage', false, data,
                            function () {
                                $('#txtName').val("");
                                $('#txtLink').val("");
                                getAllSponsors();
                            },
                            function () {
                                alert("Error happend during this update.")
                            }
                        );
                }
            }
            else {
                if (uploaderImg._storedFileIds.length > 0) {
                    uploaderImg.uploadStoredFiles();
                    $('#txtName').val("");
                    $('#txtLink').val("");
                    getAllSponsors();
                }
                else {
                    $('#upload_img_error').css('display', 'inherit');
                }
            }

            $('#insertSponsor').dialog("close");
        }
    });
});


function getAllSponsors() {
    $('#SponsorsTemp').empty();
    ajaxCall('../DataService.asmx/GetAllSponsors', false, "",
            function (msg) {
                if (msg.d == null) {
                    $('#SponsorsTemp').html("No sponsors found in the database");
                }
                else {
                    for (i in msg.d) {
                        var x = msg.d[i];
                        var jsonstr = jQuery.parseJSON(x);
                        var sponsors = [
                        { ID: jsonstr.ID, SponsorName: jsonstr.SponsorName, Link: jsonstr.Link, SponsorType: jsonstr.SponsorType }
                    ];
                        $('#SponsorTemplate').tmpl(sponsors).appendTo('#SponsorsTemp');
                    }
                }
            },
            function () {
                alert("Error happend while reading from database");
            }
        );
}

function DeleteSponsor(id) {
    if (confirm("Are you sure that you want to delete this item?")) {
        var data = '{"ID": "' + id + '"}';
        ajaxCall('../DataService.asmx/DeleteSponsor', false, data,
                function () {
                    alert("Sponsor item deleted successfully");
                    getAllSponsors();
                },
                function () {
                    alert("Error happend while deleting this item");
                }

            );
    }
}


function UpdateSponsor(id) {
    flag_insert = id;
    $('#btnInsert').html("Update");
    var data = '{"id":"' + id + '"}';
    ajaxCall('../DataService.asmx/GetSponsorByID', false, data,
            function (msg) {
                var jsonobj = jQuery.parseJSON(msg.d);
                $('#txtName').val(jsonobj.SponsorName);
                $('#txtLink').val(jsonobj.Link);
                $('#ddlTypes').val(jsonobj.SponsorType);
                $('#insertSponsor').dialog(
                {
                    modal: true,
                    closeOnEscape: false
                });
               
            },
            function () {
                alert("Error happend during this update");
            }
        );
}

function InsertSponsor() {
    flag_insert = 0;
    $('#btnInsert').html("Insert");
    $('#insertSponsor').dialog({
        modal: true,
        closeOnEscape: false
    });
}